package com.stylefeng.guns.modular.vpn_ads_manage.service.impl;

import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.common.constant.DatasourceEnum;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.mutidatasource.annotion.DataSource;
import com.stylefeng.guns.modular.vpn.config.properties.SftpProperties;
import com.stylefeng.guns.modular.vpn.utils.CommonUtil;
import com.stylefeng.guns.modular.vpn.utils.FileUtil;
import com.stylefeng.guns.modular.vpn.utils.PoiExcelUtil;
import com.stylefeng.guns.modular.vpn.utils.TimeUtil;
import com.stylefeng.guns.modular.vpn.vo.Paging;
import com.stylefeng.guns.modular.vpn_ads_manage.dao.AdsManageMapper;
import com.stylefeng.guns.modular.vpn_ads_manage.dto.AdsManageDTO;
import com.stylefeng.guns.modular.vpn_ads_manage.entity.AdsEntity;
import com.stylefeng.guns.modular.vpn_ads_manage.entity.AdsItemBO;
import com.stylefeng.guns.modular.vpn_ads_manage.service.IVpnAdsManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class VpnAdsManageServiceImpl implements IVpnAdsManageService {

    @Resource
    private AdsManageMapper manageMapper;

    @Resource(name = "imageSftp")
    private SftpProperties imageSftp;

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public Object list(AdsManageDTO dto) {
        Paging<AdsItemBO> paging = new Paging<>();
        int start = (dto.getPage() > 0 ? dto.getPage() - 1 : 0) * dto.getLimit();
        dto.setStart(start);
        paging.setItems(manageMapper.findAdsList(dto));
        paging.setTotal(manageMapper.findAdsTotalCount(dto));
        return paging;
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public void update(AdsManageDTO dto) {
        log.info("修改广告信息 开始 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        AdsItemBO itemBO = selectOneById(dto.getAdId());

        if(itemBO == null){
            throw new GunsException(BizExceptionEnum.VPN_ADS_UPDATE_NOT_EXIST);
        }

        if (StringUtils.isNotEmpty(dto.getJumpUrl()) && !CommonUtil.isUrl(dto.getJumpUrl())){
            throw new GunsException(BizExceptionEnum.VPN_ADS_UPDATE_URL_ERROR);
        }

        AdsEntity entity = new AdsEntity();

        BeanUtils.copyProperties(itemBO,entity);
        entity.setStartTime(TimeUtil.dateToGTMString(itemBO.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
        entity.setEndTime(TimeUtil.dateToGTMString(itemBO.getEndTime(),"yyyy-MM-dd HH:mm:ss"));

        //上传图片
        if(dto.getFile() != null){
            log.info("进入广告图片更新 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            String remoteFile = FileUtil.uploadFile(dto.getFile(),imageSftp);
            if(StringUtils.isEmpty(remoteFile)){
                throw new GunsException(BizExceptionEnum.VPN_UPLOAD_FILE_ERROR);
            }
            log.info("广告图片更新完成 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            entity.setAdImage(remoteFile);
        }

        if (StringUtils.isNotEmpty(dto.getStartTime())){
            entity.setStartTime(dto.getStartTime());
        }

        if (StringUtils.isNotEmpty(dto.getEndTime())){
            entity.setEndTime(dto.getEndTime());
        }

        try {
            if (TimeUtil.compareTo(entity.getStartTime(),new Date())
                    && TimeUtil.compareTo(entity.getEndTime(),new Date())){
                entity.setStatus(0);
            }else{
                if(!TimeUtil.compareTo(entity.getStartTime(),new Date())
                        && TimeUtil.compareTo(entity.getEndTime(),new Date())){
                    entity.setStatus(1);
                    entity.setStartTime(TimeUtil.dateToGTMString(new Date(),"yyyy-MM-dd HH:mm:ss"));
                }else{
                    entity.setStatus(2);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        entity.setAdName(dto.getAdName());
        entity.setAdLocation(dto.getAdLocation());
        entity.setJumpUrl(dto.getJumpUrl());
        entity.setShowType(dto.getShowType());

        manageMapper.updateAdsById(entity);
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public AdsItemBO selectOneById(int adId) {
        return manageMapper.findOneById(adId);
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    @Transactional
    public Object changeStatus(int adsId, int adsStatus) {
        AdsItemBO adsItemBO = selectOneById(adsId);
        //失效时间大于现在时间，返回1，小于返回-1，相等返回0
        int compareTo = adsItemBO.getEndTime().compareTo(new Date());
        if (compareTo > 0){
            String _startTime = TimeUtil.dateToGTMString(adsItemBO.getStartTime(),"yyyy-MM-dd HH:mm:ss");
            String _endTime = TimeUtil.dateToGTMString(adsItemBO.getEndTime(),"yyyy-MM-dd HH:mm:ss");
            if (adsStatus == 1){
                //上线，修改生效时间为当前时间
                _startTime = TimeUtil.dateToGTMString(new Date(),"yyyy-MM-dd HH:mm:ss");
            }else{
                //下线，改变失效时间为当前时间
                _endTime = TimeUtil.dateToGTMString(new Date(),"yyyy-MM-dd HH:mm:ss");
            }
            manageMapper.updateAdStatus(_startTime,_endTime,adsId,adsStatus);
            return new SuccessTip();
        }else{
//            ErrorTip errorTip = new ErrorTip(BizExceptionEnum.VPN_ADS_UPDATE_DATE_ERROR.getCode(),BizExceptionEnum.VPN_ADS_UPDATE_DATE_ERROR.getMessage());
//            return errorTip;

            manageMapper.updateAdStatus(TimeUtil.dateToGTMString(adsItemBO.getStartTime(),"yyyy-MM-dd HH:mm:ss"),TimeUtil.dateToGTMString(new Date(),"yyyy-MM-dd HH:mm:ss"),adsId,adsStatus);
            return new SuccessTip();
        }
    }

    @Override
    @DataSource(name = DatasourceEnum.DATA_SOURCE_BIZ)
    public void export(HttpServletResponse response, String adName, String adLocation, String startTime, String endTime, String showType, String status) {
        AdsManageDTO dto = new AdsManageDTO();
        dto.setAdName(adName);
        if (StringUtils.isNotEmpty(adLocation)){
            dto.setAdLocation(Integer.parseInt(adLocation));
        }
        dto.setShowType(showType);
        dto.setStartTime(startTime);
        dto.setEndTime(endTime);
        if (StringUtils.isNotEmpty(status)){
            dto.setStatus(Integer.parseInt(status));
        }

        List<AdsItemBO> items = manageMapper.findExportList(dto);

        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个Excel表单，参数为sheet的名字
        HSSFSheet sheet = workbook.createSheet("广告列表");
        List<String> colList = new ArrayList<>();
        colList.add("广告名称");
        colList.add("广告位置");
        colList.add("生效时间");
        colList.add("失效时间");
        colList.add("总观看量");
        colList.add("用户观看量");
        colList.add("点击量");
        colList.add("转化率");
        colList.add("展示人群");
        colList.add("广告状态");
        //创建表头
        PoiExcelUtil.setTableHeader(workbook,sheet,colList);

        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        for (AdsItemBO item: items){
            HSSFRow row = sheet.createRow(rowNum);
            row.createCell(0).setCellValue(item.getAdName());
            if (1 == item.getAdLocation()){
                row.createCell(1).setCellValue("首页Banner");
            }else if (2 == item.getAdLocation()){
                row.createCell(1).setCellValue("启动页");
            }else if(3 == item.getAdLocation()){
                row.createCell(1).setCellValue("首页全屏弹窗");
            }
            row.createCell(2).setCellValue(item.getStartTime()+"");
            row.createCell(3).setCellValue(item.getEndTime()+"");
            row.createCell(4).setCellValue(item.getPvCount());
            row.createCell(5).setCellValue(item.getUvCount());
            row.createCell(6).setCellValue(item.getClickCount());
            if (item.getUvCount() == 0 || item.getClickCount() == 0){
                row.createCell(7).setCellValue("0%");
            }else{
                row.createCell(7).setCellValue( ((double) item.getClickCount()/ (double) item.getUvCount()) * 100 +"%");
            }

            row.createCell(8).setCellValue(item.getShowType().replace("0","免费")
                    .replace("1","VIP")
                    .replace("2","专属线路"));

            if (0 == item.getStatus()){
                row.createCell(9).setCellValue("未上线");
            }else if (1 == item.getStatus()){
                row.createCell(9).setCellValue("已下线");
            }else if(2 == item.getStatus()){
                row.createCell(9).setCellValue("已下线");
            }

            rowNum++;
        }
        String fileName = "Ads-info-"+System.currentTimeMillis()+".xls";
        //写入文件并将文件已二进制流的方式返回为调用者
        PoiExcelUtil.writeWorkBook(response,workbook,fileName);
    }
}
